package com.xnx3.wangmarket.plugin.offlineWeixinNotification.controller;

import java.io.Console;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.DateUtil;
import com.xnx3.Lang;
import com.xnx3.StringUtil;
import com.xnx3.j2ee.entity.SmsLog;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.pluginManage.controller.BasePluginController;
import com.xnx3.j2ee.service.SmsService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.kefu.admin.util.SessionUtil;
import com.xnx3.kefu.core.bean.ChatUserBean;
import com.xnx3.kefu.core.entity.Zuoxi;
import com.xnx3.kefu.core.service.KefuService;
import com.xnx3.kefu.core.util.KefuPropertiesUtil;
import com.xnx3.kefu.core.util.TokenUtil;
import com.xnx3.kefu.core.vo.KefuVO;
import com.xnx3.wangmarket.plugin.offlineWeixinNotification.Global;
import com.xnx3.wangmarket.plugin.offlineWeixinNotification.entity.OfflineWeixinNotification;
import com.xnx3.wangmarket.plugin.offlineWeixinNotification.vo.BindVO;

/**
 * 离线通知
 * @author 管雷鸣
 */
@Controller(value="LeimingyunOfflineWeixinNotificationWXKefuController")
@RequestMapping("/plugin/offlineWeixinNotification/weixin/")
public class WeixinController extends BasePluginController{
	@Resource
	private SqlService sqlService;
	@Resource
	private UserService userService;
	@Resource
	private SmsService smsService;
	@Resource
	private KefuService kefuService;
	

	/**
	 * 这个是在微信中点击的连接，微信中点击这个连接进入咱的系统，才能拿到对方用户的openid
	 */
	@RequestMapping("entry.do")
	public String entryActivity(HttpServletRequest request,Model model){
		String kefuApi = KefuPropertiesUtil.getProperty("kefu.api");
		if(kefuApi == null || kefuApi.length() < 5) {
			return error(model, "请配置 kefu.properties 中的 kefu.api 参数");
		}
		String url = kefuApi+"/plugin/offlineWeixinNotification/weixin/wxAuthLogin.do";	//后面可以带上get传递参数，如 ?a=1&b=2   注意，这里如果实际场景中做全站加速，request.getServerName() 是不准的，直接把域名在这里写死
		url = url.replaceAll("_3F","?").replaceAll("_26","&");	//URL转码
		String jumpUrl = Global.weixin.getOauth2ExpertUrl(url);	//生成重定向的url，这个url只有在微信中才能打开，在普通浏览器是打不开的。 https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx07f3db3a6bbedfbe&redirect_uri=http://shop.imall.net.cn/plugin/weixinH5Auth/wxAuthLogin.do?storeid=1&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
		
		ActionLogUtil.insert(request, "微信入口进入，重定向", jumpUrl);
		return redirect(jumpUrl);
	}
	

	/**
	 * 微信登录 。 这里是用户访问 entry.do 然后跳转到微信授权，授权成功后自动跳转到的这里
	 * @param code 微信网页授权的code，微信授权url跳转时会自动传入过来
	 */
	@RequestMapping("wxAuthLogin.do")
	public String wxAuthLogin(HttpServletRequest request,Model model,
			@RequestParam(required = true) String code){
		ConsoleUtil.log(request.getQueryString());
		if(code.length() == 0){
			return error(model,"code未发现");
		}
		
		/**** 获取用户的openid ***/
		String openid = Global.weixin.getOauth2OpenId(code);
		if(openid == null || openid.length() == 0){
			return error(model,"获取用户openid失败");
		}
		
		/*
		 * 
		 * 
		 * 这里就已经拿到用户唯一的openid了
		 * 
		 * 
		 */
		ConsoleUtil.info("openid:"+openid);
		request.getSession().setAttribute("openid", openid);
		
		
		//userService.loginForUserId(request, user.getId()); //设置指定user.id的用户登录，进入已登录状态
		return "plugin/offlineWeixinNotification/weixin/bind";
	}

	/**
	 * test bind
	 */
	@RequestMapping("test.do")
	public String test(HttpServletRequest request,Model model){
		return "plugin/offlineWeixinNotification/weixin/bind";
	}
	
	/**
	 * 绑定成功后发送一条测试消息
	 */
	@RequestMapping("sendTest.do")
	public String sendTest(HttpServletRequest request,Model model){
		return "plugin/offlineWeixinNotification/weixin/sendTest";
	}

	/**
	 * 用户绑定
	 * @author 管雷鸣
	 * @param username 登录的用户名
	 * @param password 登录的密码
	 * @param code 验证码
	 */
	@ResponseBody
	@RequestMapping(value="bind.json",method = RequestMethod.POST)
	public BindVO bind(HttpServletRequest request, 
			@RequestParam(required = true, defaultValue="") String username,
			@RequestParam(required = true, defaultValue="") String password,
			@RequestParam(required = true, defaultValue="") String code
			){
		BindVO vo = new BindVO();
		
		String openid = (String) request.getSession().getAttribute("openid");
		ConsoleUtil.log("openid:"+openid);
		
		//验证码校验
		BaseVO capVO = com.xnx3.j2ee.util.CaptchaUtil.compare(code, request);
		if(capVO.getResult() == BaseVO.FAILURE){
			ActionLogUtil.insert(request, "用户名密码模式登录失败", "验证码出错，提交的验证码："+StringUtil.filterXss(request.getParameter("code")));
			vo.setBaseVO(BaseVO.FAILURE, capVO.getInfo());
			return vo;
		}else{
			//验证码校验通过
			
			BaseVO baseVO =  userService.loginByUsernameAndPassword(request);
			if(baseVO.getResult() == BaseVO.SUCCESS){
				//登录成功
				
				ActionLogUtil.insert(request, "用户名密码模式登录成功");
				OfflineWeixinNotification noti = sqlService.findAloneBySqlQuery("SELECT * FROM plugin_offlineweixinnotification WHERE userid="+baseVO.getInfo()+" AND openid = '"+openid+"'", OfflineWeixinNotification.class);
				if(noti != null) {
					//已经绑定过了
					vo.setBaseVO(BaseVO.FAILURE, "此客服您已经绑定过了，无需再次绑定");
					return vo;
				}
				
				//找到当前这个登录用户的kefu的chatid
				Zuoxi zuoxi = sqlService.findAloneBySqlQuery("SELECT * FROM kefu_zuoxi WHERE userid = "+baseVO.getInfo(), Zuoxi.class);
				if(zuoxi == null) {
					vo.setBaseVO(BaseVO.FAILURE, "此账号中没找到您的客服坐席！");
					return vo;
				}
				
				noti = new OfflineWeixinNotification();
				noti.setAddtime(DateUtil.timeForUnix10());
				noti.setOpenid(openid);
				noti.setUserid(Lang.stringToInt(baseVO.getInfo(), 0));
				noti.setChatid(zuoxi.getId());
				noti.setKefuid(zuoxi.getKefuid());
				sqlService.save(noti);
				
				vo.setBaseVO(BaseVO.SUCCESS, "success");
				vo.setChatid(zuoxi.getId());
				vo.setKefuapi(KefuPropertiesUtil.getProperty("kefu.api"));
				return vo;
			}else{
				ActionLogUtil.insert(request, "用户名密码模式登录失败",baseVO.getInfo());
				vo.setBaseVO(BaseVO.FAILURE, baseVO.getInfo());
				return vo;
			}
		}
	}
	
	/**
	 * 坐席用户点击微信接受到的消息，就能打开跟访客的聊天窗口进行聊天。这个就是入口
	 * @param openid 接受消息的坐席绑定的微信openid
	 * @param zuoxiChatid 接受消息的坐席人员的chatid，对应 zuoxi.chatid
	 * @param otherChatid 访客，对方的chatid
	 * 
	 */
	@RequestMapping("chat.do")
	public String chat(HttpServletRequest request,Model model,
			@RequestParam(required = true, defaultValue="") String openid,
			@RequestParam(required = true, defaultValue="") String zuoxiChatid,
			@RequestParam(required = true, defaultValue="") String otherChatid
			){
		//验证openid、zuoxiChatid是否对的起来，相当于校验
		
		String hql = "FROM OfflineWeixinNotification noti WHERE noti.openid = :openid AND chatid = :chatid";
 		Map<String, Object> parameterMap = new HashMap<String, Object>();
		parameterMap.put("openid", openid);
		parameterMap.put("chatid", zuoxiChatid);
		List<OfflineWeixinNotification> list = sqlService.findByHql(hql, parameterMap);
		if(list.size() < 1) {
			return error(model, "身份校验失败！非法进入。");
		}
		
		OfflineWeixinNotification noti = list.get(0);
		
		//将这个用户设为登录状态
		BaseVO vo = userService.loginForUserId(request, noti.getUserid());
		if(vo.getResult() - BaseVO.FAILURE == 0) {
			return error(model, "登录失败："+vo.getInfo());
		}
		
		String token = request.getSession().getId();
		ChatUserBean chatUser = new ChatUserBean();
		chatUser.setUser(getUser());
	
		//token绑定uid
		TokenUtil.bind(token, chatUser);
		//登录成功后，将当前sessionid进行缓存，以便可以根据sessionid直接取User信息
		com.xnx3.kefu.core.util.SessionUtil.setActiveUserForNotRedis(token, SessionUtil.getActiveUser());
		
		model.addAttribute("offlineWeixinNotification", list.get(0));
		model.addAttribute("otherChatid", otherChatid);
		model.addAttribute("token", token);
		return "plugin/offlineWeixinNotification/weixin/chat";
	}
}
